# -*- coding: utf8 -*-
'''
Created on 2013-7-17

@author: zengyixun
'''
import os
import json
import csv
import xml2dict
import object_dict as dict2object

class IDataException(Exception):
    pass

class DataImport:
    def __init__(self,filename=None):
        self.__datatype__ = None
        self.__dataobj__ = None
        self.__path__ = None
        if not os.path.isfile(filename):
            raise IDataException("%s is not find."%(filename))
        self.__datatype__ = os.path.splitext(filename)[1][1:].lower()
        self.__filename__ = filename
        if self.__datatype__=="xml":
            pass
        elif self.__datatype__=="json":
            pass
        elif self.__datatype__=="csv":
            pass
        else:
            raise IDataException("%s filetype:Does not support."%(self.__datatype__))
        self.update()
        
    def get(self,nodename=None):
        if nodename==None:
            return self.__dataobj__
        else:
            if self.__dataobj__.has_key(nodename):
                return self.__dataobj__[nodename]
            else:
                return None
        
    
    def update(self):
        if self.__datatype__=="xml":
            xml = xml2dict.XML2Dict()
            file = open(self.__filename__,'r')
            xmlString = ''.join(file.readlines())
            file.close()
            self.__dataobj__ = xml.fromString(xmlString).sdtest
        elif self.__datatype__=="json":
            file = open(self.__filename__,'r')
            self.__dataobj__ = json.load(file,encoding="utf-8")
            if type(self.__dataobj__) is dict:
                self.__dataobj__ = dict2object.ObjectDict(self.__dataobj__)
            file.close()
        elif self.__datatype__=="csv":
            reader = list(csv.DictReader(file(self.__filename__, 'rb')))
            self.__dataobj__ = []
            for item in reader:
                self.__dataobj__.append(dict2object.ObjectDict(item))
                

if __name__ == '__main__':
    di = DataImport("/Users/zengyixun/Documents/workspace/AliloanWebX/data/demo.xml")
    ds = di.get()
    print ds.TestB
    
    
    
    